<template>
  <div class="qrtzJobRecord">
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
      class="layout-content"
    >
      <a-space>
        <a-button type="primary" @click="flush"> 刷新 </a-button>
        <a-button type="primary" @click="openAdd"> 新增 </a-button>
      </a-space>

      <!-- 新增模态窗口 -->
      <a-modal
        v-model="visible"
        :title="isEdit ? '编辑' : '新增'"
        @ok="handleOk"
        cancelText="取消"
        okText="确认"
        :closable="closable"
        @cancel="handleCancel"
      >
        <a-form
          :form="form"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-form-item label="id" hidden>
            <a-input v-decorator="['id']" />
          </a-form-item>
          <a-form-item label="任务名称">
            <a-input
              v-decorator="[
                'jobName',
                {
                  rules: [{ required: true, message: '请输入任务名称!' }],
                },
              ]"
              :disabled="!isEdit ? disabled : ''"
            />
          </a-form-item>
          <a-form-item label="任务组名称">
            <a-input
              v-decorator="[
                'groupName',
                {
                  rules: [{ required: true, message: '请输入任务组名称!' }],
                },
              ]"
              :disabled="!isEdit ? disabled : ''"
            />
          </a-form-item>
          <a-form-item label="cron表达式">
            <a-input
              v-decorator="[
                'cronExpress',
                {
                  rules: [{ required: true, message: '请输入cron表达式!' }],
                },
              ]"
            />
          </a-form-item>
          <div v-if="!isEdit">
            <a-form-item label="任务参数">
              <a-input
                v-decorator="[
                  'jobParam',
                  {
                    rules: [{ required: false, message: '请输入任务参数!' }],
                  },
                ]"
              />
            </a-form-item>
            <a-form-item label="重试次数">
              <a-input
                v-decorator="[
                  'retryCount',
                  {
                    rules: [{ required: true, message: '请输入重试次数!' }],
                  },
                ]"
              />
            </a-form-item>
            <a-form-item label="重试间隔">
              <a-input
                v-decorator="[
                  'retryInterval',
                  {
                    rules: [{ required: true, message: '请输入重试间隔!' }],
                  },
                ]"
              />
            </a-form-item>
          </div>
        </a-form>
      </a-modal>
      <!-- 列表 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :rowKey="
          (record, index) => {
            return index;
          }
        "
        :scroll="{ x: 1080, y: 400 }"
        :pagination="pagination"
        @change="handlePage"
        :loading="loading"
      >
        <span slot="action" slot-scope="record">
          <a @click="pause(record)">暂停</a>
          <a-divider type="vertical" />
          <a @click="resume(record)">恢复</a>
          <a-divider type="vertical" />
          <a @click="run(record)">立即执行</a>
          <a-divider type="vertical" />
          <a @click="openEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleRemove(record)">删除</a>
        </span>
      </a-table>
    </a-layout-content>
  </div>
</template>

<script>
import { add, getPage, edit, remove, pause, run, resume } from "@/api/job";
import { notification, Modal } from "ant-design-vue";
import "ant-design-vue/lib/notification/style/css";
import zhCN from "ant-design-vue/es/locale/zh_CN";

export default {
  name: "qrtzJobRecord",
  data() {
    return {
      visible: false,
      form: this.$form.createForm(this, { name: "coordinated" }),
      scrollY: 400,
      loading: false,
      closable: false,
      isEdit: false,
      disabled: false,
      code: "",
      description: "",
      locale: zhCN,
      showToday: true,
      jobStatusItems: window.JOB_STATUS_ARRAY,
      pagination: {
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"],
        showTotal: (total, range) =>
          "显示" +
          range[0] +
          " ~ " +
          range[1] +
          "条记录，共" +
          total +
          "条记录",
        pageSize: 10,
        current: 1,
        total: 0,
      },
      columns: [
        {
          title: "任务名称",
          dataIndex: "jobName",
          key: "jobName",
          align: "center",
          width: 150,
        },
        {
          title: "组名称",
          dataIndex: "groupName",
          key: "groupName",
          align: "center",
          width: 150,
        },
        {
          title: "cron表达式",
          dataIndex: "cronExpress",
          key: "cronExpress",
          align: "center",
          width: 150,
        },
        {
          title: "任务参数",
          dataIndex: "jobParam",
          key: "jobParam",
          align: "center",
          width: 150,
        },
        {
          title: "重试次数",
          dataIndex: "retryCount",
          key: "retryCount",
          align: "center",
          width: 150,
        },
        {
          title: "重试间隔",
          dataIndex: "retryInterval",
          key: "retryInterval",
          align: "center",
          width: 150,
        },
        {
          title: "任务状态",
          dataIndex: "jobStatus",
          key: "jobStatus",
          align: "center",
          width: 150,
          customRender: (text, record, index) => {
            const jobStatusItem = this.jobStatusItems.find(
              (item) => item.code === text
            );
            //如果jobStatusItem === 4或者 jobStatusItem=== 5就显示为红色,其他显示绿色
            if (jobStatusItem.code === '4' || jobStatusItem.code === '5') {
              return <a-tag color="volcano">{jobStatusItem.message}</a-tag>;
            } else if (jobStatusItem.code === '2') {
              return <a-tag color="orange">{jobStatusItem.message}</a-tag>;
            } else {
              return <a-tag color="green">{jobStatusItem.message}</a-tag>;
            }
          },
        },
        {
          title: "下一次执行时间",
          dataIndex: "nextFireTime",
          key: "nextFireTime",
          align: "center",
          width: 150,
        },
        {
          title: "上一次执行时间",
          dataIndex: "preFireTime",
          key: "preFireTime",
          align: "center",
          width: 150,
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
          align: "center",
          width: 150,
        },
        {
          title: "更新时间",
          dataIndex: "updateTime",
          key: "updateTime",
          align: "center",
          width: 150,
        },
        {
          title: "操作",
          key: "operation",
          fixed: "right",
          width: 200,
          scopedSlots: { customRender: "action" },
        },
      ],
      data: [],
    };
  },
  mounted() {
    this.handlePage();
  },
  methods: {
    handleOk(e) {
      this.form.validateFields((err, values) => {
        if (err) {
          return;
        } else {
          this.handleAddOrEdit(values);
        }
      });
    },
    async handleAddOrEdit(values) {
      if (this.isEdit) {
        //发起更新请求
        await edit(values).then((res) => {
          this.description = "更新成功";
          this.code = res.code;
        });
      } else {
        //发起新增请求
        await add(values).then((res) => {
          this.description = "添加成功";
          this.code = res.code;
        });
      }
      if (this.code === 200) {
        notification.success({
          message: "消息提示",
          description: this.description,
          duration: 2,
        });
        //关闭表单
        this.visible = false;
        //清空表单
        this.form.resetFields();
        //刷新表格
        this.handlePage({
          current: this.pagination.current,
          pageSize: this.pagination.pageSize,
        });
      }
    },
    handleCancel(e) {
      this.form.resetFields();
    },
    flush() {
      this.handlePage();
    },
    handlePage(pagination, filters, sorter) {
      this.loading = true;
      const pageNo = pagination === undefined ? 1 : pagination.current;
      const pageSize = pagination === undefined ? 10 : pagination.pageSize;
      getPage(pageNo, pageSize).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          //设置每页码和每页显示数
          this.pagination.current = pageNo;
          this.pagination.pageSize = pageSize;
          //获取结果
          const qrtzJobRecordList = res.data.data;
          this.data = qrtzJobRecordList;
          this.pagination.total = res.data.total;
        } else {
          notification.error({
            message: "消息提示",
            description: res.message,
            duration: 3,
          });
        }
      });
    },
    openEdit(record) {
      this.isEdit = true;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          id: record.id,
          jobName: record.jobName,
          groupName: record.groupName,
          cronExpress: record.cronExpress,
        });
      });
      this.visible = true;
    },
    openAdd() {
      this.isEdit = false;
      this.visible = true;
    },
    handleRemove(record) {
      Modal.confirm({
        title: "是否确认删除?",
        okText: "是",
        okType: "danger",
        cancelText: "否",
        centered: true,
        onOk: () => {
          remove(record).then((res) => {
            if (res.code === 200) {
              notification.success({
                message: "消息提示",
                description: "乘客删除成功",
                duration: 2,
              });
              this.handlePage({
                current: this.pagination.current,
                pageSize: this.pagination.pageSize,
              });
            } else {
              notification.error({
                message: "消息提示",
                description: res.message,
                duration: 2,
              });
            }
          });
        },
      });
    },
    pause(record) {
      Modal.confirm({
        title: "是否确认暂停?",
        okText: "是",
        okType: "danger",
        cancelText: "否",
        centered: true,
        onOk: () => {
          pause(record).then((res) => {
            if (res.code === 200) {
              notification.success({
                message: "消息提示",
                description: "暂停成功",
                duration: 2,
              });
              this.handlePage({
                current: this.pagination.current,
                pageSize: this.pagination.pageSize,
              });
            }
          });
        },
      });
    },
    resume(record) {
      resume(record).then((res) => {
        if (res.code === 200) {
          notification.success({
            message: "消息提示",
            description: "恢复成功",
          });
          this.handlePage({
            current: this.pagination.current,
            pageSize: this.pagination.pageSize,
          });
        }
      });
    },
    run(record) {
      run(record).then((res) => {
        if (res.code === 200) {
          notification.success({
            message: "消息提示",
            description: "执行成功",
          });
          this.handlePage({
            current: this.pagination.current,
            pageSize: this.pagination.pageSize,
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.ant-input {
  width: 300px;
}
.ant-table-wrapper {
  margin-top: 20px;
}
/deep/ .ant-table-header {
  padding-bottom: 0 !important;
}
/deep/ .ant-select-selection--single {
  width: 110px !important;
}
/deep/ .ant-table-thead > tr > th {
  border-bottom: 0 !important;
}
</style>
